package com.hmall.trade.Listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.Constants.MQConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {
    private final IOrderService orderService;
    private final PayClient payClient;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MQConstants.DELAY_QUEUE_NAME),
            exchange =@Exchange(value = MQConstants.DELAY_EXCHANGE_NAME,delayed = "true"),
            key = MQConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Long orderId){
      //1.查询本地订单状态是否为已支付
        Order order = orderService.getById(orderId);
       if (order == null || order.getStatus() != 1){
           return;
       }
        //2.利用openfeign查询支付服务订单状态是否为已支付
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        //3.如果订单状态为已支付，更改本地订单状态为已支付
        if (payOrderDTO.getStatus() == 3){
            orderService.markOrderPaySuccess(orderId);
        }else{
            orderService.cancalOrder(orderId);
        }
      // 4.如果订单状态为未支付，取消本地订单状态，或者更改本地订单状态为已取消或者超时
      //5.恢复库存
    }
}
